package com.saui.traceu;

import java.util.ArrayList;
import java.util.List;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.CheckedTextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Projection;
import com.saui.traceu.controller.SessionManager;
import com.saui.traceu.model.Session;
import com.saui.traceu.model.TraceDBAdapter;
import com.saui.traceu.view.TraceOverlay;

public class TraceMapHistory extends MapActivity{

	private TraceDBAdapter dbAdapter;
	private Cursor theCursor;
	private SessionManager sessionManager;
	private Projection projection;
	
	private List<TraceOverlay> tracesList = new ArrayList<TraceOverlay>();
	private long[] sessionIDs;
	private Menu mapHistoryMenu;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);   

		MapView mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		projection = mapView.getProjection();
		registerForContextMenu(mapView);
		
		dbAdapter = new TraceDBAdapter(this);
		dbAdapter.open();
		
	
		//Intent receiver from TraceList class
		//receives an StringArrayList with active Session Ids (sessions to display on map);
		Bundle extras = getIntent().getExtras();
	    if( extras != null ){
	       sessionIDs = extras.getLongArray("sessionIDs");
	       
	    }
	    
	    
	    // iterate through session ids to create geopoints then
	    // draw those geopoints onto an overlay
		for(int i=0; i< (int)sessionIDs.length ;i++){
			// We take our session data points (list of gps coordiantes)
			//and put them into a GeoPoint list for use when drawing on the map
			List<GeoPoint> geoPointList = getSessionPoints(sessionIDs[i]);
			
			//now that we have our geoPointList of gps coordinates we draw them
			drawSession(mapView, sessionIDs[i], geoPointList, Color.BLUE);
		}

		//draw my current location overlay
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);
		myLocationOverlay.enableMyLocation();
		
//		mapView.getController().animateTo(new GeoPoint((int)(32.65049*1e6),(int)(-16.90097*1e6)));
	}
    
	
	@Override
	protected boolean isRouteDisplayed() 
	{
		// TODO Auto-generated method stub
		return false;
	}
	
	
	/*
	 * Creates and draws a TraceOverlay for a list of geoPoints
	 */
	private void drawSession(MapView mapview, long sessionId, List<GeoPoint> pointsList, int color)
	{
		//create a new custom overlay object
		TraceOverlay traceOverlay = new TraceOverlay(pointsList,color);
		
		//tell the overlay object what session we want drawn 
		//overlay object will handle getting the geopoints.
		traceOverlay.setSessionId(sessionId);
		mapview.getOverlays().add(traceOverlay);
		tracesList.add(traceOverlay);
	}
	
	
	
	/*
	 * Get tracePoints list from the database for each session 
	 */
	private List<GeoPoint> getSessionPoints(long sessionID)
	{	
		//TODO: Database getTracePointsBySessionId which receives SessionId as an argument instead of Session
		ArrayList<GeoPoint> geoPointsList = new ArrayList<GeoPoint>();
		theCursor = dbAdapter.getTracePointsByLongID(sessionID);
		startManagingCursor(theCursor);
		theCursor.moveToFirst();
		
		//initiate variables for gettng gps data
		double latitude;
		double longitude;
		GeoPoint point;
		
		//cycle through cursor drawing out gps coordinates
		while(!theCursor.isAfterLast()){
				//gps coordinates from cursor
			   latitude = theCursor.getDouble(theCursor.getColumnIndexOrThrow(TraceDBAdapter.KEY_DATA_LAT));
			   longitude = theCursor.getDouble(theCursor.getColumnIndexOrThrow(TraceDBAdapter.KEY_DATA_LONG));
			   // put those gps coordinates into a GeoPoint Object
			   point = new GeoPoint((int)(latitude*1e6), (int)(longitude*1e6));
			   // add GeoPoint to list
			   geoPointsList.add(point);
			   
			   theCursor.moveToNext();
		 }
		theCursor.close();
		
		return geoPointsList;
	}

	//TODO: implement a dataBaseObserver? Detect automatically changes on the data being displayed.
	
	/**
	 * @param text String to toast to screen
	 */
	public void printTester(String text){
		Toast.makeText(this,text,Toast.LENGTH_LONG).show();
	}


	/**
	* Populate the options for the "Menu" button
	*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	   	inflater.inflate(R.menu.menu_tracemaphistory, menu);
	   	return true;
	}

	 
    /**
	 * handle option menu events.
	 * 
	 */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	
    	// Handle item selection
    	int itemnum = item.getItemId();
    	
        switch (itemnum) {
        case R.id.tracemaphistory_back:
        	//go back to list view
        	Intent backListView = new Intent(this, TraceList.class);
        	startActivity(backListView);
            return true;
        case R.id.livemap_goto:
        	//go back to live map view
        	Intent backLiveMap = new Intent(this, TraceMap.class);
        	startActivity(backLiveMap);
		    return true;
  
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}
